/*
*
* 	@description layui表格字段模糊搜索
* 	@author 李豪
*	@gitee gitee.com/LiDongyo/casual-search
*
* */
layui.define(['table','jquery'],function(exports){
	var table = layui.table,
		$ = layui.jquery,
		cacheData = [],
		cacheTables = [],
		tempData = [],
		isFirstRender = [],
		inputsValue = [],
		elem_search = '.casual-search',
		//字符常量
		ELEM_TOOL = '.layui-table-tool',
		ELEM_TOOL_SELF = '.layui-table-tool-self',
		//配置
		config = {
			'title' : '字符搜素',
			'table' : {}
			}
	var module = {
		render : function(options){
			//初始化配置
			options = this.initConfig(options);

			let that = this,
				currTable = options.table,
				currData,
				casualSearchHtml,
				currTableDom = $($(currTable.elem)[0].nextSibling),
				layToolHtml = '<div class="'+ELEM_TOOL.substr(1)+'"></div>',
				layToolSelfHtml = '<div class="'+ELEM_TOOL_SELF.substr(1)+'"></div>';

			elem_search += '-'+currTable.id;
			casualSearchHtml = that.buildDom(currTable,currTableDom);
			cacheTables[currTable.id] = currTable;
 			//是否需要渲染工具栏
			if((currTable.toolbar !== 'default' || typeof currTable.toolbar !== 'string') && currTableDom.find(ELEM_TOOL).length === 0){
				currTableDom.prepend(layToolHtml);
			}

			//是否需要渲染工具栏右侧
			if(currTableDom.find(ELEM_TOOL_SELF).length === 0){
				currTableDom.find(ELEM_TOOL).append(layToolSelfHtml);
			}

			//插入casual-search
			currTableDom.find(ELEM_TOOL_SELF).append(casualSearchHtml);

			//填入上次输入的值，并选中
			if(inputsValue[currTable.id] !== undefined){
				$(elem_search+' input').val(inputsValue[currTable.id]);
				$(elem_search+' input').focus();
			}

			currData = that.getTableData(currTable);

			//如果是第一次render注册事件
			if(isFirstRender.indexOf(currTable.id) < 0){
				//数据加载
				cacheData[currTable.id] = currData;
				//注册事件
				that.registerEvents(currTable);

				isFirstRender.push(currTable.id);
			}

			//如果获取的数据与上次数据有差异,则证明执行了后端搜索,重新获取缓存数据
			if(JSON.stringify(currData) !== JSON.stringify(tempData)){
				cacheData[currTable.id] = currData;
			}

			//最后初始化casual-search
			elem_search = '.casual-search';
		},
		//初始化配置
		initConfig : function(options){
			for (let key in options){
				if(key in config){
					config[key] = options[key];
				}
			}
			return config;
		},
		//注册事件
		registerEvents : function(currTable){
			var that = this;
			$(document).on('click',elem_search+' button',function(){
				that.setInputsValue(currTable.id,$(this).parent('div').find('input').val());
				that.search($(this).parent('div').find('input').val(),currTable);
			})
			$(document).on('keyup',elem_search+' input',function(event){
				if(event.keyCode === 13){
					that.setInputsValue(currTable.id,$(this).val());
					that.search($(this).val(),currTable)
				}
			})
		},
		//记录输入框的值
		setInputsValue : function(tableId,value){
			inputsValue[tableId] = value;
		},
		//开始搜索
		search : function(value,currTable){
			let tableId = currTable.id,
				that = this;
			tempData = [];
			//如果不为空才搜索，否则返回全部
			if(value){
				if(cacheData[tableId].length > 0){
					value = value.trim().toLowerCase();
					that.changingData(tableId,value);
				}

			}else{
				tempData = cacheData[tableId];
			}
			that.reloadData(currTable);
		},
		//改变数据
		changingData : function(tableId,value){
			let type = ['number','string'],
				str = '',
				lay_table_index = 0;
			for (let index in cacheData[tableId]){
				for (let key in cacheTables[tableId]['cols'][0]){
					str = cacheData[tableId][index][cacheTables[tableId]['cols'][0][key]['field']];

					if(type.indexOf(typeof str) > -1 && str.toString().toLowerCase().indexOf(value) > -1){
						cacheData[tableId][index]['LAY_TABLE_INDEX'] = lay_table_index;
						tempData.push(cacheData[tableId][index]);
						lay_table_index++;
						break;
					}

				}
			}

		},
		//重载表格
		reloadData : function(currTable){
			let url = '';
			if('url' in currTable && currTable.url){
				url = currTable.url;
			}
			table.reload(
				currTable.id,{
				url : '',
				data : tempData
			});
			cacheTables[currTable.id]['url'] = url;
		},
		//构建dom
		buildDom : function(currTable,currTableDom){
			let style = '';
			// if((currTable.toolbar !== 'default' || typeof currTable.toolbar !== 'string') && currTableDom.find(ELEM_TOOL).length === 0){
				style = 'position:relative;bottom:4px;left:7px;'
			// }
			return '<div class="layui-inline '+elem_search.substr(1)+'" style="display: inline-flex;'+style+'" title="'+config.title+'"><input type="text" class="layui-input" /><button style="margin-left: 7px;" type="button" table-id="'+currTable.id+'" class="layui-btn"><i class="layui-icon layui-icon-search"></i>'+config.title+'</button></div>';
		},
		//获取表格数据
		getTableData : function(currTable){
			return table.cache[currTable.id] || currTable.data;
		}
	}

	exports('casualSearch',module);
})
